import config from '../common/config.js';
import user from '../common/user.js'
// 超时时间
const timeout = 60000;
// 返回类型
const responseType = "application/json;charset=utf8";
export async function request(method,url,data={},header={},isRequest=false){
	url = config.webUrl+url
	// 如果需要添加token
	if(header.authorization){
		//判断用户是否登录
		// checkToken 表示要检查token
		if(header.checkToken&&!user.token){
			return uni.navigateTo({
				url:"/pages/login/login"
			});
		}
		header.authorization=user.token?user.token:null;
		
	}
	let res  = {code:0,msg:"",data:null};
	if(isRequest){
		res = await uni.uploadFile({
			url,
			fileType:"image",
			filePath:data,
			header,
			timeout,
			method,
			name:"file",
			dataType:"json",
			responseType,
			
		}).catch(e=>console.error(e))
		const {code,msg,data:d} = (new Function("return"+res.data))();
		if(code==200){
			return d;
		}
	}else {
		 res = await uni.request({
			url,
			method,
			responseType,
			dataType:"json",
			header,
			data,
			timeout,
		}).catch(e=>console.error(e))
		console.log(res)
		const {code,msg,data:d} = res.data;
		if(code==200){
			return d;
		}
		
		if(code==80001){
			uni.navigateTo({
				url:"/pages/login/login"
			});
		}else {
			uni.showToast({
				title:msg,
				icon:"none",
			})
		}
	}
	
	return Promise.reject(res.data)
}



